<template>
  <div>
    <a-page-header style="border: 1px solid rgb(235, 237, 240)"
      :title="json.baseinfo.name + '(' + isOnlineStr + ', 更新时间:' + onTime + ')'" @back="() => null">
      <a-card title="操作">
        <a-row>
          <a-col span=2>
            <a-button v-show="json.baseinfo.isOnline != 1" @click="handleConnect">连接</a-button><a-button
              @click="handleDisconnect" v-show="json.baseinfo.isOnline == 1">断开</a-button>
          </a-col>
          <a-col span=10 class="">
            <a-divider type="vertical" />
            <a-button @click="handleChannelSetting">设置通道</a-button>
            <a-divider type="vertical" />
            <a-button @click="handleSetConfig">设置参数信息</a-button>
            <!-- <a-divider type="vertical" />
          <a-button  @click="handleConnect">设置报警状态</a-button> -->
          </a-col>
        </a-row>
      </a-card>
      <a-card title="实时信息">
        <a-row style="text-align:center;">
          <a-col span=2>
            <div class="ant-statistic">
              <div class="ant-statistic-title">是否异常</div>
              <div class="ant-statistic-content"><a-icon :style="isWarning(json.baseinfo.isWarning) + ';font-size:25px;'"
                  type="warning" /></div>
            </div>

          </a-col>
          <a-col span=2><a-statistic title="输入状态" :value="input" style="margin-right: 20px" /></a-col>
          <a-col span=2><a-statistic title="输出状态" :value="output" style="margin-right: 20px" /></a-col>
          <a-col span=3><a-statistic :title="'主电电压(' + json.baseinfo.mainVolMin + '--' + json.baseinfo.mainVolMax + 'V)'"
              :value="json.baseinfo.mainVol + 'V'" style="margin-right: 20px" /></a-col>
          <a-col span=3><a-statistic :title="'备电电压(' + json.baseinfo.backVolMin + '--' + json.baseinfo.backVolMax + 'V)'"
              :value="json.baseinfo.backVol + 'V'" style="margin-right: 20px" /></a-col>
          <a-col span=3><a-statistic :title="'供电电流(最大:' + json.baseinfo.mainCurMax + 'A)'"
              :value="json.baseinfo.supplyCurrent + 'A'" style="margin-right: 20px" /></a-col>
          <a-col span=6><a-statistic
              :title="'温度(最高:' + json.baseinfo.tempMax + '­°C, 风扇最大温度:' + json.baseinfo.fanTempMax + '­°C)'"
              :value="json.baseinfo.temp + '­°C'" style="margin-right: 20px" /></a-col>
        </a-row>
      </a-card>
      <a-card>
        <a-row>
          <a-col span=6>
            <a-card title="网络信息" :bordered="false">
              <a-row>
                <a-col span=12>
                  <p>ip:{{ json.network.ip }}</p>
                  <p>port:{{ json.network.port }}</p>
                  <p>网关:{{ json.network.gateway }}</p>
                </a-col>
                <a-col>
                  <p>MAC:{{ json.network.mac }}</p>
                  <p>DNS:{{ json.network.dns }}</p>
                  <p>mask:{{ json.network.subnet }}</p>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
          <a-col span=17 style="padding-left:10px;">
            <a-card title="异常信息">
              <a-col span=4 v-for="(item, index) in wanringList" v-bind:key="index" style="text-align:center">
                <div><a-icon :style="isWarning(item.value) + ';font-size:25px;'" type="warning" /></div>
                <div>{{ item.name }}</div>
              </a-col>
            </a-card>
          </a-col>
        </a-row>
      </a-card>

      <a-card>
        <a-row>
          <table>
            <tr>
              <th>类型-端口号</th>
              <th v-for="item in json.switches.switches" :key="item.id">{{ item.name }}</th>
            </tr>
            <tr>
              <th>电流(A)</th>
              <td v-for="item in json.switches.switches" :key="item.id"><span v-show="item.current > 0">{{ item.current
              }}</span></td>
            </tr>
            <tr>
              <th>电压(V)</th>
              <td v-for="item in json.switches.switches" :key="item.id"><span v-show="item.voltage > 0">{{ item.voltage
              }}</span></td>
            </tr>
            <tr>
              <th>控制电流(A)</th>
              <td v-for="item in json.switches.switches" :key="item.id"><span v-show="item.controlC > 0">{{ item.controlC
              }}</span></td>
            </tr>
            <tr>
              <th>异常</th>
              <td v-for="item in json.switches.switches" :key="item.id"><span v-if="item.iswarning == '0'">-</span><span
                  v-else><a-icon style="color:red;" type="exclamation-circle" /></span></td>
            </tr>
            <tr>
              <th>开关</th>
              <td v-for="item in json.switches.switches" :key="item.id"><span v-show="item.state == 0">开</span><span
                  v-show="item.state == 1" style="color:red;">关</span></td>
            </tr>
          </table>
        </a-row>
      </a-card>
    </a-page-header>
    <a-button @click="handleShowDetail">显示/隐藏设备数据结构</a-button>
    <a-row v-show="showDetail">
      <a-col :span="24">
        <vue-json-editor v-model="json" :show-btns="true" :expandedOnStart="true"
          @json-save="onJsonSave"></vue-json-editor>
      </a-col>
    </a-row>
    <TigDeviceChannelSettingModal ref="tigDeviceChannelSettingModal"></TigDeviceChannelSettingModal>
    <TigDeviceConfigSetModal ref="tigDeviceConfigSetModal"></TigDeviceConfigSetModal>
  </div>
</template>


<script>

import { httpAction, getAction } from '@/api/manage'
import { getDeviceinfo } from '@/api/deviceApi'
import store from '@/store/'
import vueJsonEditor from 'vue-json-editor'
import { connectDevice, disConnectDevice } from '@/api/deviceApi'
import { formatDate } from '@/utils/util'
import TigDeviceChannelSettingModal from './popups/TigDeviceChannelSettingModal'

import TigDeviceConfigSetModal from './popups/TigDeviceConfigSetModal'

export default {
  name: 'TigDeviceInfo',
  components: {
    vueJsonEditor,
    TigDeviceChannelSettingModal,
    TigDeviceConfigSetModal
  },
  props: {

  },
  data() {
    return {
      model: {},

      checked: false,
      json: {
        baseinfo: {},
        network: {},
        warning: {},
        switches: {
          total: 0,
          switches: []
        }
      },
      lockReconnect: false,
      deviceId: '',
      showDetail: false,
    }
  },
  computed: {
    isOnline() {//computed需要监听data中的属性才能刷新页面
      return this.json.baseinfo.isOnline
    },
    isOnlineStr: function () {
      this.$forceUpdate();
      return this.json.baseinfo.isOnline == '1' ? '在线' : '离线';
    },
    onTime: function () {
      if (this.json.onTime)
        return formatDate(this.json.onTime, 'yyyy-MM-dd hh:mm:ss')
    },
    offTime: function () {
      if (this.json.offTime)
        return formatDate(this.json.offTime, 'yyyy-MM-dd hh:mm:ss')
    },
    input: function () {
      if (this.json.baseinfo.input == '0')
        return '主'
      if (this.json.baseinfo.input == '1')
        return '备'
      if (this.json.baseinfo.input == '2')
        return '双'
    },
    output: function () {
      if (this.json.baseinfo.output == '0')
        return '主'
      if (this.json.baseinfo.output == '1')
        return '备'
    },
    wanringList: function () {
      return [{ name: '市电异常', value: this.json.warning.cityVol }, { name: '主电异常', value: this.json.warning.mainVol },
      { name: '总电流异常', value: this.json.warning.current }, { name: 'UPS异常', value: this.json.warning.ups },
      { name: '备电压异常', value: this.json.warning.backVol }, { name: '温度异常', value: this.json.warning.temp }]
    },
  },
  created() {
    this.deviceId = this.$route.query.deviceId;
    this.loadData()
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    view(record) {
      //this.model = record
    },
    loadData() {
      var _that = this
      getDeviceinfo({ deviceId: this.deviceId }).then((res) => {
        if (res.success) {
          let data = JSON.parse(res.message)
          if (data.shadow != null) {
            _that.json = data.shadow;
            _that.record = data;
          }
          else {
            _that.json = data;
          }
        }
      })
    },
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id;
      var url = window._CONFIG['WS_URL'] + "/deviceWebsocket/" + this.deviceId;
      // var url = window._CONFIG['WS_URL'] + "/deviceWebsocket/"+this.deviceId;
      console.log("svalue", url)
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function () {
      console.log("设备WebSocket连接成功");
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      console.log("设备WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage: function (e) {
      var data = eval("(" + e.data + ")"); //解析对象
      if (data.shadow != null) {
        this.json = data.shadow;
        this.record = data;
      }
      else{
        this.json = data;
      }
      // if(this.json.baseinfo.isOnline == 0){
      //   console.log('webSocketMsg isOnline == 0')
      // }
      //console.log('webSocketMsg：' + JSON.stringify(data))
      if (data.cmd) {
        if (data.cmd == 'ACK') {
          if (data.cmdStr == "" || data.cmdStr == undefined) {
           // this.$message.info("指令成功下发")
          } else {
           // this.$message.info("指令下发失败")
          }
        }
      }
    },
    websocketOnclose: function (e) {
      console.log("connection closed (" + e + ")");
      if (e) {
        console.log("connection closed (" + e.code + ")");
      }
      this.reconnect();
    },
    websocketSend(text) { // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },
    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    onJsonSave() {

    },
    handleConnect() {
      connectDevice({ deviceId: this.deviceId }).then(res => {
        this.$message.info("连接已发送")
      });
    },
    handleDisconnect() {
      disConnectDevice({ deviceId: this.deviceId }).then(res => {
        this.$message.info("请求已发送")
      });
    },
    isWarning(num) {
      if (num == 1) return 'color:red'
      else return 'color:gray'
    },
    handleShowDetail() {
      this.showDetail = !this.showDetail
    },
    handleChannelSetting() {
      this.$refs.tigDeviceChannelSettingModal.edit(this.json)
    },
    handleSetConfig() {
      this.$refs.tigDeviceConfigSetModal.edit(this.json)
    }

  }
}
</script>

<style lang="less" scoped>
table {
  font-size: 15px;
  width: 100%;
}

th,
td {
  padding: 2px;
  border: 1px solid black;
}

.ant-card {
  margin-top: 10px;
}

.ant-card-bordered {
  border: 0px;
}
</style>